//
//  HistoryDataBase.m
//  Express
//
//  Created by lanou on 16/1/14.
//  Copyright © 2016年 FJY. All rights reserved.
//

#import "HistoryDataBase.h"
#import <BmobSDK/Bmob.h>


@implementation HistoryDataBase

static HistoryDataBase *historyDB;
+ (HistoryDataBase *)shareHistoryDataBase {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        historyDB = [[HistoryDataBase alloc] init];
    });
    return historyDB;
}

/*
- (NSString *)historyDBPath:(NSString *)path {
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *DBPath = [documentPath stringByAppendingPathComponent:path];
    return DBPath;
}

- (void)openHistoryDBWithPath:(NSString *)path {
    self.historyDB = [FMDatabase databaseWithPath:[self historyDBPath:path]];
}

- (void)createDBTableWithName:(NSString *)tableName {
    if (!_historyDB) {
        [self openHistoryDBWithPath:@"/HistoryDataBase"];
    }
    if ([_historyDB open]) {
        NSString *createString = [NSString stringWithFormat:@"CREATE TABLE %@(ExpressNumber TEXT PRIMARY KEY, ExpressCode TEXT, ExpressCompanyName TEXT, ExpressTel TEXT,ExpressStatus TEXT)",tableName];
        BOOL isCreateSuccess = [_historyDB executeUpdate:createString];
        if (isCreateSuccess) {
            NSLog(@"create success");
        } else {
            NSLog(@"create fail");
        }
    }
}

- (void)insertModel:(Express *)expressModel tableWithName:(NSString *)tableName {
    
    [self openHistoryDBWithPath:@"/HistoryDataBase"];
    
    if (!expressModel) {
        return;
    }
    if ([_historyDB open]) {
        NSString *insertModel = [NSString stringWithFormat:@"insert into %@(ExpressNumber, ExpressCode, ExpressCompanyName, ExpressTel, ExpressStatus) values(?,?,?,?,?)",tableName];
        BOOL isInsertSuccess = [_historyDB executeUpdate:insertModel,expressModel.expressOrderNumber,expressModel.expressCode,expressModel.expressName,expressModel.expressTelephone,expressModel.expressStatus];
        if (isInsertSuccess) {
            [self insertDataToCloudDBWithModel:expressModel];
            NSLog(@"insert success");
        } else {
            NSLog(@"insert fail");
        }
    }
}

- (void)deleteModel:(Express *)expressModel tableWithName:(NSString *)tableName {
    if (!_historyDB) {
        [self openHistoryDBWithPath:@"/HistoryDataBase"];
    }
    if ([_historyDB open]) {
        NSString *deleteModel = [NSString stringWithFormat:@"delete from %@ where ExpressNumber = %@",tableName,expressModel.expressOrderNumber];
        BOOL isDeleteSuccess = [_historyDB executeUpdate:deleteModel];
        if (isDeleteSuccess) {
            NSLog(@"delete success");
        } else {
            NSLog(@"delete fail");
        }
    }
}

- (NSMutableArray *)selectModelsWithtableWithName:(NSString *)tableName {
    if (!_historyDB) {
        [self openHistoryDBWithPath:@"/HistoryDataBase"];
    }
    NSMutableArray *modelsArray = [NSMutableArray array];
    if ([_historyDB open]) {
        NSString *selectString = [NSString stringWithFormat:@"select *from %@",tableName];
        FMResultSet *modelsSet = [_historyDB executeQuery:selectString];
        while ([modelsSet next]) {
            Express *express = [[Express alloc] init];
            express.expressCode = [modelsSet stringForColumn:@"ExpressCode"];
            express.expressOrderNumber = [modelsSet stringForColumn:@"ExpressNumber"];
            express.expressTelephone = [modelsSet stringForColumn:@"ExpressTel"];
            express.expressName = [modelsSet stringForColumn:@"ExpressCompanyName"];
            express.expressStatus = [modelsSet stringForColumn:@"ExpressStatus"];
            [modelsArray addObject:express];
        }
    }
    return modelsArray;
}

*/



- (NSArray *)expressesArray {
    if (_expressesArray != nil) {
        _expressesArray = [[NSArray alloc] init];
    }
    return _expressesArray;
}


#pragma mark -------------- cloud DB --------------

- (void)insertSingleDataToCloudDBWithModel:(Express *)expressModel {
    BmobObject *queryHistory = [BmobObject objectWithClassName:@"QueryHistory"];
    [queryHistory setObject:expressModel.expressOrderNumber forKey:@"ExpressOrderNumber"];
    [queryHistory setObject:expressModel.expressName forKey:@"ExpressCompanyName"];
    [queryHistory setObject:expressModel.expressStatus forKey:@"ExpressStatus"];
    [queryHistory setObject:expressModel.expressCode forKey:@"ExpressCode"];
    [queryHistory setObject:expressModel.expressTelephone forKey:@"ExpressTel"];
    
    //异步保存到服务器
    [queryHistory saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"%@",queryHistory);
        } else if (error) {
            NSLog(@"%@",[[error userInfo] objectForKey:@"error"]);
        } else {
            NSLog(@"UNkonw error");
        }
    }];

}

- (void)deleteSingleDataFromCloudDBWithModel:(Express *)expressModel {
    BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"QueryHistory" objectId:expressModel.objectId];
    [bmobObject deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"云 delte success");
        } else if (error) {
            NSLog(@"%@",[[error userInfo] objectForKey:@"error"]);
        } else {
            NSLog(@"UNkonw error");
        }
    }];
}

- (Express *)selectSingleDataFromCloudDBWithModel:(Express *)expressModel {
    Express *express = [[Express alloc] init];
    BmobQuery *bmobQuery = [BmobQuery queryWithClassName:@"QueryHistory"];
    [bmobQuery getObjectInBackgroundWithId:expressModel.objectId block:^(BmobObject *object, NSError *error) {
        if (error){
            //进行错误处理
            NSLog(@"%@",error);
        }else{
            if (object) {
                express.expressCode = [object objectForKey:@"ExpressCode"];
                express.expressOrderNumber = [object objectForKey:@"ExpressOrderNumber"];
                express.expressTelephone = [object objectForKey:@"ExpressTel"];
                express.expressName = [object objectForKey:@"ExpressCompanyName"];
                express.expressStatus = [object objectForKey:@"ExpressStatus"];
                express.objectId = [object objectForKey:@"objectId"];
                express.createdAt = [object objectForKey:@"createdAt"];
                express.updatedAt = [object objectForKey:@"updatedAt"];
            }
        }
    }];
    return express;
}


- (NSMutableArray *)selectMultipleDataFromCloudDB {
    NSMutableArray *modelsArray = [NSMutableArray array];
    BmobQuery *bmobQuery = [BmobQuery queryWithClassName:@"QueryHistory"];
    [bmobQuery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (BmobObject *obj in array) {
            Express *express = [[Express alloc] init];
            express.expressCode = [obj objectForKey:@"ExpressCode"];
            express.expressOrderNumber = [obj objectForKey:@"ExpressOrderNumber"];
            express.expressTelephone = [obj objectForKey:@"ExpressTel"];
            express.expressName = [obj objectForKey:@"ExpressCompanyName"];
            express.expressStatus = [obj objectForKey:@"ExpressStatus"];
            express.objectId = [obj objectForKey:@"objectId"];
            express.createdAt = [obj objectForKey:@"createdAt"];
            express.updatedAt = [obj objectForKey:@"updatedAt"];
            [modelsArray addObject:express];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myExpressQuery" object:nil];
    }];
    self.expressesArray = modelsArray;
    return modelsArray;
}


- (void)updateFromCloudDBWithModel:(Express *)expressModel {
    BmobObject *queryHistory = [BmobObject objectWithClassName:@"QueryHistory"];
    [queryHistory setObject:expressModel.expressStatus forKey:@"ExpressStatus"];
    [queryHistory updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"更新成功，以下为对象值，可以看到score值已经改变");
            NSLog(@"%@",queryHistory);
        } else {
            NSLog(@"%@",error);
        }
    }];
}


@end
